<?php
/**
 * Author: 孙武 QQ:1228746736
 * Date: 2017/11/4
 * Time: 7:57
 */

namespace Addons\WeChatApi;

class WeChatUser
{

    private $_appid;//appid
    private $_secret;//secret

    public function __construct($appid, $secret)
    {
        $this->_appid = $appid;
        $this->_secret = $secret;
    }


    /**
     * 获取access_token和openid
     * @return array
     */
    private function getWebAccessTokenAndOpenId()
    {
        $code = $_GET['code'];//用户点授权后获得的code
        $webAccessTokenAPI = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$this->_appid&secret=$this->_secret&code=$code&grant_type=authorization_code";
        $webAccessTokenAPIRes = $this->doGet($webAccessTokenAPI);
        $webAccessTokenAPIRes = json_decode($webAccessTokenAPIRes, true);
        $accessToken = $webAccessTokenAPIRes['access_token'];
        $openId = $webAccessTokenAPIRes['openid'];
        return array($accessToken, $openId);
    }

    /**
     * 获取用户信息
     * @return array
     */
    public function getUserInfo()
    {
        $res = $this->getWebAccessTokenAndOpenId();
        $accessToken = $res[0];
        $openId = $res[1];
        $userInfoAPI = "https://api.weixin.qq.com/sns/userinfo?access_token=$accessToken&openid=$openId&lang=zh_CN";
        $userInfoAPIRes = $this->doGet($userInfoAPI);
        $userInfo = json_decode($userInfoAPIRes, true);
        return $userInfo;
    }



    /**
     * 获取auth跳转的地址
     * @param $redirectUrl 用户回调的地址
     * @param int $type 获取信息的类型:1  snsapi_base  2:snsapi_userinfo  默认:snsapi_userinfo
     */
    public function getAuthUrl($redirectUrl, $type = 2)
    {
        $targetUrl = urlencode($redirectUrl);

        $scope = 'snsapi_userinfo';
        if ($type == 1) {
            $scope = 'snsapi_base';
        } else if ($type == 2) {
            $scope = 'snsapi_userinfo';
        }
        $codeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$this->_appid&redirect_uri=$targetUrl&response_type=code&scope=$scope&state=STATE#wechat_redirect";
        return $codeUrl;
    }


    /**
     * Httpget请求
     * @param $url
     * @return mixed
     */
    private function doGet($url)
    {
        //初始化
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL,$url);
        // 执行后不直接打印出来
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 不从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        //执行并获取HTML文档内容
        $output = curl_exec($ch);

        //释放curl句柄
        curl_close($ch);

        return $output;
    }

}